<template>
  <ElDialog
    v-model="dialogVisible"
    :title="`SKU管理 - ${itemData?.itemName || ''}`"
    width="1000px"
    :close-on-click-modal="false"
    destroy-on-close
  >
    <div class="sku-management">
      <!-- 工具栏 -->
      <div class="toolbar">
        <ElButton type="primary" @click="addSku">
          <ElIcon><Plus /></ElIcon>
          新增SKU
        </ElButton>
        <ElButton @click="refreshSkuList">
          <ElIcon><Refresh /></ElIcon>
          刷新
        </ElButton>
      </div>

      <!-- SKU列表 -->
      <ElTable
        :data="skuList"
        v-loading="loading"
        border
        stripe
        style="width: 100%"
      >
        <ElTableColumn type="index" label="序号" width="60" align="center" />

        <ElTableColumn prop="skuCode" label="SKU编码" width="120" />

        <ElTableColumn prop="skuName" label="SKU名称" min-width="150" />

        <ElTableColumn prop="barcode" label="条形码" width="120" />

        <ElTableColumn prop="specifications" label="规格描述" min-width="120" />

        <ElTableColumn
          prop="weight"
          label="重量(kg)"
          width="100"
          align="center"
        >
          <template #default="{ row }">
            {{ row.weight || "-" }}
          </template>
        </ElTableColumn>

        <ElTableColumn
          prop="volume"
          label="体积(m³)"
          width="100"
          align="center"
        >
          <template #default="{ row }">
            {{ row.volume || "-" }}
          </template>
        </ElTableColumn>

        <ElTableColumn
          prop="inventory"
          label="库存数量"
          width="100"
          align="center"
        >
          <template #default="{ row }">
            <ElTag :type="getInventoryTagType(row.inventory)">
              {{ row.inventory || 0 }}
            </ElTag>
          </template>
        </ElTableColumn>

        <ElTableColumn label="操作" width="150" align="center" fixed="right">
          <template #default="{ row }">
            <ElButton type="primary" link @click="editSku(row)">
              <ElIcon><Edit /></ElIcon>
              编辑
            </ElButton>
            <ElButton type="danger" link @click="deleteSku(row)">
              <ElIcon><Delete /></ElIcon>
              删除
            </ElButton>
          </template>
        </ElTableColumn>
      </ElTable>
    </div>

    <template #footer>
      <ElButton @click="handleClose">关闭</ElButton>
    </template>

    <!-- SKU编辑弹窗 -->
    <ElDialog
      v-model="skuEditVisible"
      :title="skuEditTitle"
      width="600px"
      :close-on-click-modal="false"
      append-to-body
    >
      <ElForm
        ref="skuFormRef"
        :model="skuFormData"
        :rules="skuFormRules"
        label-width="100px"
      >
        <ElFormItem label="SKU编码" prop="skuCode">
          <ElInput
            v-model="skuFormData.skuCode"
            placeholder="请输入SKU编码"
            :disabled="skuEditType === 'edit'"
          />
        </ElFormItem>

        <ElFormItem label="SKU名称" prop="skuName">
          <ElInput v-model="skuFormData.skuName" placeholder="请输入SKU名称" />
        </ElFormItem>

        <ElFormItem label="条形码" prop="barcode">
          <ElInput v-model="skuFormData.barcode" placeholder="请输入条形码" />
        </ElFormItem>

        <ElFormItem label="规格描述" prop="specifications">
          <ElInput
            v-model="skuFormData.specifications"
            placeholder="如：红色/L码、500ml等"
          />
        </ElFormItem>

        <ElRow :gutter="16">
          <ElCol :span="12">
            <ElFormItem label="重量(kg)" prop="weight">
              <ElInputNumber
                v-model="skuFormData.weight"
                :min="0"
                :precision="3"
                placeholder="重量"
                style="width: 100%"
              />
            </ElFormItem>
          </ElCol>

          <ElCol :span="12">
            <ElFormItem label="体积(m³)" prop="volume">
              <ElInputNumber
                v-model="skuFormData.volume"
                :min="0"
                :precision="6"
                placeholder="体积"
                style="width: 100%"
              />
            </ElFormItem>
          </ElCol>
        </ElRow>
      </ElForm>

      <template #footer>
        <ElSpace>
          <ElButton @click="skuEditVisible = false">取消</ElButton>
          <ElButton
            type="primary"
            @click="handleSkuSubmit"
            :loading="skuSubmitLoading"
          >
            确定
          </ElButton>
        </ElSpace>
      </template>
    </ElDialog>
  </ElDialog>
</template>

<script setup lang="ts">
import { ref, computed, watch } from "vue";
import { listSku, addSku, updateSku, delSku } from "@/api/wms/item";
import { ElMessage, ElMessageBox } from "element-plus";
import { Plus, Refresh, Edit, Delete } from "@element-plus/icons-vue";
import type { FormInstance, FormRules } from "element-plus";

defineOptions({ name: "WmsSkuDialog" });

// Props
interface Props {
  visible: boolean;
  itemData?: WMS.Item.ItemInfo | null;
}

const props = withDefaults(defineProps<Props>(), {
  visible: false,
  itemData: null,
});

// Emits
interface Emits {
  (e: "update:visible", visible: boolean): void;
  (e: "submit"): void;
}

const emit = defineEmits<Emits>();

// 弹窗状态
const dialogVisible = computed({
  get: () => props.visible,
  set: (value) => emit("update:visible", value),
});

// SKU列表
const skuList = ref<WMS.Item.SkuInfo[]>([]);
const loading = ref(false);

// SKU编辑弹窗
const skuEditVisible = ref(false);
const skuEditType = ref<"add" | "edit">("add");
const skuEditTitle = computed(() =>
  skuEditType.value === "add" ? "新增SKU" : "编辑SKU",
);
const skuSubmitLoading = ref(false);

// SKU表单
const skuFormRef = ref<FormInstance>();
const skuFormData = ref<Partial<WMS.Item.SkuInfo>>({});

// SKU表单验证规则
const skuFormRules: FormRules = {
  skuCode: [{ required: true, message: "请输入SKU编码", trigger: "blur" }],
  skuName: [{ required: true, message: "请输入SKU名称", trigger: "blur" }],
};

// 监听弹窗显示
watch(
  () => props.visible,
  (visible) => {
    if (visible && props.itemData) {
      refreshSkuList();
    }
  },
);

// 获取库存标签类型
const getInventoryTagType = (inventory: number) => {
  if (inventory === 0) return "danger";
  if (inventory < 10) return "warning";
  return "success";
};

// 刷新SKU列表
const refreshSkuList = async () => {
  if (!props.itemData?.id) return;

  loading.value = true;
  try {
    const response = await listSku(props.itemData.id);
    skuList.value = response.data || [];
  } catch (error) {
    console.error("获取SKU列表失败:", error);
    ElMessage.error("获取SKU列表失败");
  } finally {
    loading.value = false;
  }
};

// 新增SKU
const addSku = () => {
  skuEditType.value = "add";
  skuFormData.value = {
    itemId: props.itemData?.id,
    skuCode: "",
    skuName: "",
    barcode: "",
    specifications: "",
    weight: undefined,
    volume: undefined,
  };
  skuEditVisible.value = true;
};

// 编辑SKU
const editSku = (row: WMS.Item.SkuInfo) => {
  skuEditType.value = "edit";
  skuFormData.value = { ...row };
  skuEditVisible.value = true;
};

// 删除SKU
const deleteSku = async (row: WMS.Item.SkuInfo) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除SKU"${row.skuName}"吗？`,
      "删除确认",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      },
    );

    await delSku(row.id);
    ElMessage.success("删除成功");
    refreshSkuList();
    emit("submit");
  } catch (error) {
    if (error !== "cancel") {
      ElMessage.error("删除失败");
    }
  }
};

// 提交SKU表单
const handleSkuSubmit = async () => {
  try {
    await skuFormRef.value?.validate();

    skuSubmitLoading.value = true;

    if (skuEditType.value === "add") {
      await addSku(skuFormData.value);
      ElMessage.success("新增SKU成功");
    } else {
      await updateSku(skuFormData.value);
      ElMessage.success("更新SKU成功");
    }

    skuEditVisible.value = false;
    refreshSkuList();
    emit("submit");
  } catch (error) {
    console.error("提交失败:", error);
    ElMessage.error("操作失败，请稍后重试");
  } finally {
    skuSubmitLoading.value = false;
  }
};

// 关闭弹窗
const handleClose = () => {
  dialogVisible.value = false;
};
</script>

<style lang="scss" scoped>
.sku-management {
  .toolbar {
    margin-bottom: 16px;
    display: flex;
    gap: 8px;
  }
}
</style>
